#ifndef __SE_MUTEX_LOCK_HPP__
#define __SE_MUTEX_LOCK_HPP__

#include "NonCopyable.hpp"
#include <pthread.h>

namespace se {

class MutexLock final : public NonCopyAble {
    friend class Condition;
public:
    /**
     * @brief 初始化锁
     */
    MutexLock() {
        pthread_mutex_init(&_mutex, nullptr);
    }

    /**
     * @brief 销毁锁
     */
    ~MutexLock() {
        pthread_mutex_destroy(&_mutex);
    }

    /**
     * @brief 加锁
     */
    void lock() {
        pthread_mutex_lock(&_mutex);
    }

    /**
     * @brief 尝试加锁
     * @return int 加锁成功时返回0，加锁失败时返回EBUSY
     */
    int trylock() {
        int ret = pthread_mutex_trylock(&_mutex);
        return ret;
    }

    /**
     * @brief 解锁
     */
    void unlock() {
        pthread_mutex_unlock(&_mutex);
    }

private:
    pthread_mutex_t _mutex;
};

//实现自动上锁自动解锁
class MutexLockGuard {
public:
    /**
     * @brief 构造时创建锁并加锁
     */
    MutexLockGuard(MutexLock & mutex)
    : _mutex(mutex) {_mutex.lock();}

    /**
     * @brief 析构时自动解锁
     */
    ~MutexLockGuard() {_mutex.unlock();}
private:
    MutexLock & _mutex;
};

}  // end of namesapce se

#endif
